<template>
  <div class="content">
    <!-- 互动社区 顶部搜索栏 -->
    <div class="top-contain">
      <div class="logoBlock">
        <!-- <el-avatar :size="50"></el-avatar>
                <div>用户名</div> -->
        <h1>互动社区</h1>
      </div>
      <div class="searchQuestion">
        <el-input placeholder="搜索问题" class="input-with-select" v-model="keyWords" @keydown.enter.native="searchForumQuestion(keyWords)"> </el-input
        ><el-button slot="append" icon="el-icon-search" @click="searchForumQuestion(keyWords)">搜索</el-button>
      </div>
      <div class="writeQuestion">
        <h2 @click="askQuestion()">提问</h2>
      </div>
    </div>

    <div class="m-contain">
      <div class="question-msg">
            <p id="msg-title"><b>发起人</b></p>
            <div id="auth-msg">
                <el-avatar shape="square" :size="80" :src="question.avatar"></el-avatar>
                <span id="auth-nickname" :class="[{'teacher_identification': Number(question.sign) === 1}]"><b>{{question.nickname}}</b></span>
            </div>
            <div id="related-quesiton">
                <p id="related-title"><b>相关问题</b></p>
                <ul v-for="relatedQuestion in relatedQuestions" :key="relatedQuestion.id">
                  <li><el-link :underline="false" :href="'/forum/' + relatedQuestion.id" style="text-decoration:none; font-size: 20px">{{relatedQuestion.title}}</el-link></li>
                  <!-- <li><router-link :to="{path: '/forum/' + relatedQuestion.id}" style="text-decoration:none; color: #409EFF; font-size: 20px">{{relatedQuestion.title}}</router-link></li> -->
                </ul>
            </div>
      </div>
      <div class="question-content">
            <p id="question-title"><b>{{question.title}}</b></p>
            <p>作者：{{question.nickname}}  |  发布时间：{{question.gmtModified}}  |  阅读数：{{question.viewCount}}</p>
            <el-divider></el-divider>
            <!-- <div>{{question.description}}</div> -->
            <div class="markdown-body" v-html="question.description"></div>
            <el-divider></el-divider>
            <p>
              <el-tag v-for="tag in questionTags" :key="tag">
                {{tag}}
              </el-tag>
            </p>
            <el-divider></el-divider>
            <p>
            <el-link icon="el-icon-edit" v-if="isCreator" :href="'/editQuestion/' + question.id">编辑</el-link>
            </p>
      </div>
      <div class="question-reply">
        <p class="reply-count"><b>{{question.commentCount}}个回复</b></p>
        <div class="reply-list" v-for="(items, indexOfFirstLevelReply) in replyList" :key="items.replyQuestionVo.id">
          <el-avatar shape="square" :size="40" :src="items.replyQuestionVo.creatorAvatar"></el-avatar>
          <div class="reply-desc">
            <p class="title"><span :class="[{'teacher_identification': Number(items.replyQuestionVo.creatorSign) === 1}]">{{items.replyQuestionVo.creatorNickname}}</span><span class="auth-tag" v-if="items.replyQuestionVo.creatorId === question.creatorId">作者</span></p>
            <!-- <p class="desc">{{items.replyQuestionVo.description}}</p> -->
            <div class="desc markdown-body" v-html="items.replyQuestionVo.description"></div>
            <div class="operator">
              <div class="reply-time">{{items.replyQuestionVo.gmtModified}}</div>
              <div>
                <i class="el-icon-star-off" :ref="'like' + items.replyQuestionVo.id" @click="likeOperatorUseInFirstLevelReply(items, indexOfFirstLevelReply)" style="margin-right: 10px">{{items.replyQuestionVo.likeCount}}</i>
                <i class="el-icon-chat-dot-square" :ref="'reply' + items.replyQuestionVo.id" @click="replyOperatorUseInFirstLevelReply(items, indexOfFirstLevelReply)">{{items.replyQuestionVo.commentCount}}</i>
                <div class="item-edit-reply-list" v-if="items.replyQuestionVo.show">
                  <!-- <mavon-editor ref=md  @imgAdd="imgAdd" :toolbars="toolbars" :placeholder="'回复 ' + item.id"/> -->
                  <div class="reply-list" v-for="(item, indexOfSecondLevelReply) in items.childrenList" :key="item.replyQuestionVo.id">
                    <!-- <p>哈哈哈</p>
                    <p>{{index}}</p> -->
                    <el-avatar shape="square" :size="40" :src="item.replyQuestionVo.creatorAvatar"></el-avatar>
                    <div class="reply-desc">
                      <p class="title"><span :class="[{'teacher_identification': Number(item.replyQuestionVo.creatorSign) === 1}]">{{item.replyQuestionVo.creatorNickname}}</span><span class="auth-tag" v-if="item.replyQuestionVo.creatorId === question.creatorId">作者</span>
                        <span v-if="items.replyQuestionVo.creatorId !== item.replyQuestionVo.recipientId">&nbsp;&nbsp;<i class="el-icon-arrow-right" style="font-size: 14px"></i>&nbsp;&nbsp;<span :class="[{'teacher_identification': Number(item.replyQuestionVo.recipientSign) === 1}]">{{item.replyQuestionVo.recipientNickname}}</span><span class="auth-tag" v-if="item.replyQuestionVo.recipientId === question.creatorId">作者</span></span>
                      </p>
                      <!-- <p class="desc">{{item.replyQuestionVo.description}}</p> -->
                      <div class="desc markdown-body" v-html="item.replyQuestionVo.description"></div>
                      <div class="operator">
                        <div class="reply-time">{{item.replyQuestionVo.gmtModified}}</div>
                        <div>
                          <i class="el-icon-star-off" :ref="'like' + item.replyQuestionVo.id" @click="likeOperatorUseInSecondLevelReply(item, indexOfFirstLevelReply, indexOfSecondLevelReply)" style="margin-right: 10px">{{item.replyQuestionVo.likeCount}}</i>
                          <!-- <i class="el-icon-chat-dot-square" :ref="'reply' + item.replyQuestionVo.id" @click="replyOperatorUseInSecondLevelReply(item, indexOfFirstLevelReply, indexOfSecondLevelReply)">{{item.replyQuestionVo.commentCount}}</i> -->
                          <i class="el-icon-chat-dot-square" :ref="'reply' + item.replyQuestionVo.id" @click="replyOperatorUseInSecondLevelReply(item, indexOfFirstLevelReply, indexOfSecondLevelReply)"></i>
                          <div class="item-edit-reply" v-if="item.replyQuestionVo.show">
                            <mavon-editor v-model="contentInReplySecondLevel" ref=md  @imgAdd="imgAdd" :toolbars="toolbars" :placeholder="'回复 ' + item.replyQuestionVo.creatorNickname"/>
                            <div class="submit-area">
                              <el-button type="success" id="submit-btn" @click="replyInSecondLevel(item, indexOfFirstLevelReply, indexOfSecondLevelReply)">回复</el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <mavon-editor ref=md v-model="contentInReplySecondLevel" @imgAdd="imgAdd" :toolbars="toolbars" :placeholder="'回复 ' + items.replyQuestionVo.creatorNickname"/>
                    <div class="submit-area">
                      <el-button type="success" id="submit-btn" @click="replyInSecondLevelToFirstLevel(items, indexOfFirstLevelReply)">回复</el-button>
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>
        <p class="edit-reply-title"><b>提交回复</b></p>
        <div class="edit-reply">
          <div class="creator-msg">
            <el-avatar shape="square" :size="80" :src="userInfo.avatar"></el-avatar>
            <span class="creator-nickname" :class="[{'teacher_identification': Number(userInfo.sign) === 1}]"><b>{{userInfo.nickname}}</b></span>
          </div>
          <mavon-editor v-model="contentInReplyFirstLevel" ref=md  @imgAdd="imgAdd" :toolbars="toolbars"/>
          <div class="submit-area">
            <el-button type="success" id="submit-btn" @click="replyInFirstLevel()">回复</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import cookie from "js-cookie";
import forumApi from '@/api/forum'
import 'github-markdown-css/github-markdown.css' // 然后添加样式markdown-body

export default {
  asyncData({ params, error }) {
     return {questionId: params.id}
   },

  data() {
    return {
        url: 'https://s1.ax1x.com/2023/04/03/pphIDK0.jpg',
        question: {},
        isCreator: false,
        userInfo: {},
        contentInReplyFirstLevel: '',
        contentInReplySecondLevel: '',
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: false, // 标记
          superscript: false, // 上角标
          subscript: false, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: false, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: false, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: false, // 下一步
          trash: false, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: false, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
          boxShadow: false
        },
        questionTags: [],
        relatedQuestions: [],
        replyList: [],
        keyWords: ''
    };
  },

  created() {
    this.getQuestionById()
    this.getList(this.questionId, 0, 'true')
  },

  methods: {
    searchForumQuestion(keyWords) {
      this.$router.push({path:'/forum/', query:{searchKeyWords:keyWords}})
    },

    getList(questionId, parentId, userDesc) {
      forumApi.getList(questionId, parentId, userDesc).then(response => {
        this.replyList = response.data.data.list
        for (let i = 0; i < this.replyList.length; i++) {
          var reply = this.replyList[i]
          var MarkdownIt = require('markdown-it'),
          md = new MarkdownIt();
          var result = md.render(reply.replyQuestionVo.description);
          this.replyList[i].replyQuestionVo.description = result
        }
      })
    },

    replyOperatorUseInSecondLevelReply(item, indexOfFirstLevelReply, indexOfSecondLevelReply) {
      //获取二级列表
      forumApi.getList(this.questionId, item.replyQuestionVo.id, 'false').then(response => {
        // this.replyList[indexOfFirstLevelReply].childrenList[indexOfSecondLevelReply].childrenList = response.data.data.list
        item.replyQuestionVo.show = !item.replyQuestionVo.show
      })
    },

    //在二级列表处点赞
    likeOperatorUseInSecondLevelReply(item, indexOfFirstLevelReply, indexOfSecondLevelReply) {
      var formNameClass = this.$refs['like' + item.replyQuestionVo.id][0].getAttribute("class")
      if (formNameClass === "el-icon-star-off") {
        this.$refs['like' + item.replyQuestionVo.id][0].setAttribute("class", "el-icon-star-on");
        // this.il[formName].like_count = 3

        this.replyList[indexOfFirstLevelReply].childrenList[indexOfSecondLevelReply].replyQuestionVo.likeCount = this.replyList[indexOfFirstLevelReply].childrenList[indexOfSecondLevelReply].replyQuestionVo.likeCount + 1
        //更新数据库信息
        forumApi.likeOperator(item.replyQuestionVo.id).then(response => {})
      } else {
        this.$refs['like' + item.replyQuestionVo.id][0].setAttribute("class", "el-icon-star-off");
        this.replyList[indexOfFirstLevelReply].childrenList[indexOfSecondLevelReply].replyQuestionVo.likeCount = this.replyList[indexOfFirstLevelReply].childrenList[indexOfSecondLevelReply].replyQuestionVo.likeCount - 1
        //更新数据库信息
        forumApi.cancelLikeOperator(item.replyQuestionVo.id).then(response => {})
      }
    },

    replyOperatorUseInFirstLevelReply(item, index) {
      //获取二级列表
      forumApi.getList(this.questionId, item.replyQuestionVo.id, 'false').then(response => {
        this.replyList[index].childrenList = response.data.data.list
        // console.log('试一下这里')
        // console.log(this.replyList[index].childrenList) //包含childrenList replyQuestionVo

        for (let i = 0; i < this.replyList[index].childrenList.length; i++) {
          var reply = this.replyList[index].childrenList[i]
          // console.log(i)
          // console.log(reply.replyQuestionVo.description)
          // 将内容转为markdown格式
          var MarkdownIt = require('markdown-it'),
          md = new MarkdownIt();
          var result = md.render(reply.replyQuestionVo.description);
          this.replyList[index].childrenList[i].replyQuestionVo.description = result
        }

        //修改评论数
        this.replyList[index].replyQuestionVo.commentCount = this.replyList[index].childrenList.length
        item.replyQuestionVo.show = !item.replyQuestionVo.show
      })
    },

    //在一级列表处点赞
    likeOperatorUseInFirstLevelReply(item, index) {
      var formNameClass = this.$refs['like' + item.replyQuestionVo.id][0].getAttribute("class")
      if (formNameClass === "el-icon-star-off") {
        this.$refs['like' + item.replyQuestionVo.id][0].setAttribute("class", "el-icon-star-on");
        // this.il[formName].like_count = 3
        this.replyList[index].replyQuestionVo.likeCount = this.replyList[index].replyQuestionVo.likeCount + 1
        //更新数据库信息
        forumApi.likeOperator(item.replyQuestionVo.id).then(response => {})
      } else {
        this.$refs['like' + item.replyQuestionVo.id][0].setAttribute("class", "el-icon-star-off");
        this.replyList[index].replyQuestionVo.likeCount = this.replyList[index].replyQuestionVo.likeCount - 1
        //更新数据库信息
        forumApi.cancelLikeOperator(item.replyQuestionVo.id).then(response => {})
      }
    },

    //在二级列表里对一级列表里的内容进行回复
    replyInSecondLevelToFirstLevel(items, indexOfFirstLevelReply) {
      var replyInSecondLevelVo = {
        questionId: this.questionId,
        parentId: items.replyQuestionVo.id,
        type: '1',
        creatorId: this.userInfo.id,
        recipientId: items.replyQuestionVo.creatorId,
        description: this.contentInReplySecondLevel,
      }
      forumApi.replyOperatorInFirstLeve(replyInSecondLevelVo).then(response => {
        this.getCommentCount()
        //如果是自己给自己回复，则不需要发送消息通知
        if (replyInSecondLevelVo.creatorId !== replyInSecondLevelVo.recipientId) {
          var forumNotification = {}
          forumNotification.notifier = replyInSecondLevelVo.creatorId
          forumNotification.receiver = replyInSecondLevelVo.recipientId
          forumNotification.questionId = replyInSecondLevelVo.questionId
          forumNotification.type = replyInSecondLevelVo.type
          forumNotification.questionTitle = this.question.title
          this.addNotification(forumNotification)
        }
        this.$message({
          message: '成功评论',
          type: 'success'
        });
        this.contentInReplySecondLevel = ''
         this.replyOperatorUseInFirstLevelReply(this.replyList[indexOfFirstLevelReply], indexOfFirstLevelReply)
         this.replyList[indexOfFirstLevelReply].replyQuestionVo.show = !this.replyList[indexOfFirstLevelReply].replyQuestionVo.show
      })
    },

    //在二级列表里对二级列表里的内容进行回复
    replyInSecondLevel(item, indexOfFirstLevelReply, indexOfSecondLevelReply) {
      var replyInSecondLevelVo = {
        questionId: this.questionId,
        parentId: item.replyQuestionVo.parentId,//保持一致
        type: '1',
        creatorId: this.userInfo.id,
        recipientId: item.replyQuestionVo.creatorId,
        description: this.contentInReplySecondLevel,
      }
      
      forumApi.replyOperatorInFirstLeve(replyInSecondLevelVo).then(response => {
        this.getCommentCount()
        //如果是自己给自己回复，则不需要发送消息通知
        if (replyInSecondLevelVo.creatorId !== replyInSecondLevelVo.recipientId) {
          var forumNotification = {}
          forumNotification.notifier = replyInSecondLevelVo.creatorId
          forumNotification.receiver = replyInSecondLevelVo.recipientId
          forumNotification.questionId = replyInSecondLevelVo.questionId
          forumNotification.type = replyInSecondLevelVo.type
          forumNotification.questionTitle = this.question.title
          this.addNotification(forumNotification)
        }
        this.$message({
          message: '成功评论',
          type: 'success'
        });
        this.contentInReplySecondLevel = ''
        this.replyOperatorUseInFirstLevelReply(this.replyList[indexOfFirstLevelReply], indexOfFirstLevelReply)
        this.replyList[indexOfFirstLevelReply].replyQuestionVo.show = !this.replyList[indexOfFirstLevelReply].replyQuestionVo.show
      })

    },

    // 格式化时间
    // timestampToTime(times) {
    //   let time = times[1]
    //   let mdy = times[0]
    //   mdy = mdy.split('/')
    //   let month = parseInt(mdy[0]);
    //   let day = parseInt(mdy[1]);
    //   let year = parseInt(mdy[2])
    //   return year + '-' + month + '-' + day + ' ' + time
    // },

    //在一级列表处进行回复
    replyInFirstLevel() {
      var replyInFirstLevelVo = {
        questionId: this.questionId,
        parentId: '0',
        type: '0',
        creatorId: this.userInfo.id,
        recipientId: this.question.creatorId,
        description: this.contentInReplyFirstLevel
      }

      forumApi.replyOperatorInFirstLeve(replyInFirstLevelVo).then(response => {
        this.getCommentCount()
        //如果是自己给自己回复，则不需要发送消息通知
        if (replyInFirstLevelVo.creatorId !== replyInFirstLevelVo.recipientId) {
          var forumNotification = {}
          forumNotification.notifier = replyInFirstLevelVo.creatorId
          forumNotification.receiver = replyInFirstLevelVo.recipientId
          forumNotification.questionId = replyInFirstLevelVo.questionId
          forumNotification.type = replyInFirstLevelVo.type
          forumNotification.questionTitle = this.question.title
          this.addNotification(forumNotification)
        }
        this.$message({
          message: '成功评论',
          type: 'success'
        });
        this.contentInReplyFirstLevel = ''
        this.getList(this.questionId, 0, 'true')
      })


    },

    //生成一条消息通知，通知接收者
    addNotification(forumNotification) {
      forumApi.addNotification(forumNotification).then(response => {

      })
    },

    //获取话题总评论数
    getCommentCount() {
      forumApi.getCommentCount(this.questionId).then(response => {
        this.question.commentCount = response.data.data.commentCount
      })
    },

    //markdown编辑器的 图片上传功能
    imgAdd(pos, $file) {
      var formdata = new FormData();
      formdata.append('image', $file);
      console.log(formdata)
      forumApi.uploadOssFile(formdata)
        .then(response => {
            this.$refs.md.$img2Url(pos, response.data.data.url)
      })

    },

    JudgeCreator() {
      //从cookie获取用户信息
      var userStr = cookie.get('ucenter')
      // 把字符串转换json对象(js对象)
      if(userStr) {
        this.userInfo = (JSON.parse(userStr))
        if (this.userInfo.id === this.question.creatorId) {
          this.isCreator = true
        }
      }
    },

    //根据话题ID获取话题信息
    getQuestionById() {
      forumApi.getQuestionById(this.questionId).then(response => {
        this.question = response.data.data.question
        // 将内容转为markdown格式
        var MarkdownIt = require('markdown-it'),
        md = new MarkdownIt();
        var result = md.render(this.question.description);
        this.question.description = result
        //展示标签
        this.questionTags = this.question.tag.split('|')
        //根据标签获取相关问题
        forumApi.relatedQuestion(this.question.id, this.question.tag).then(response => {
          this.relatedQuestions = response.data.data.relatedQuestions
        })
        //编辑 是否显示
        this.JudgeCreator()
      })
    },

    askQuestion() {
      this.$router.push('/editQuestion')
    }, 
  },
};
</script>

<style scoped>
h1 {
  font-size: 28px;
  /* color: #7c7c7c; */
}

h2 {
  font-size: 20px;
  /* color: #7c7c7c; */
}

.content {
  /* 上 右 下 左 */
  margin: 10px 0px 0px 0px;
  /* padding-bottom: 100px; */
}

.top-contain {
  max-width: 1150px;
  margin: 0 auto;
  align-items: center;
  display: flex;
  position: relative;
}
.logoBlock {
  width: 10%;
  padding: 5px;
  display: inline-block;
}
.searchQuestion {
  vertical-align: top;
  display: inline-block;
  position: absolute;
  left: 150px;
}
.el-input {
  /* 搜索框长度 */
  width: 300px;
  margin-right: 10px;
}
.writeQuestion {
  /* https://blog.csdn.net/qq_44131760/article/details/104755826  解释了为什么使用 vertical-align*/
  vertical-align: top;
  display: inline-block;
  position: absolute;
  right: 10px;
}

.m-contain {
  max-width: 1150px;
  margin: 0 auto;
  margin-top: 20px;
}

.question-content {
    width: 70%;
}

.question-msg {
    float: right;
    width: 28%;
    height: 77px;
}

#question-title {
    font-size: 24px;
}

#msg-title {
    font-size: 24px;
}

#auth-msg {
    margin-top: 10px;
    margin-bottom: 10px;
}

.el-avatar {
    vertical-align: middle;
}

#auth-nickname, .creator-nickname {
    margin-left: 10px;
    font-size: 20px;
}

#related-title {
    font-size: 24px;
    margin-top: 20px;
}

.question-reply {
  width: 70%;
}

.reply-count {
  font-size: 25px;
  border-bottom: 1px solid #DCDFE6;
  padding-top: 10px;
  padding-bottom: 10px;
}

.reply-list {
  width: 100%;
  margin-top: 20px;
  border-bottom: 1px solid #DCDFE6;
}

.reply-desc {
  width: 89%;
  vertical-align: top;
  display: inline-block;
}

.reply-desc .title {
  font-size: 18px;
  margin-left: 5px;
  margin-bottom: 5px;
  font-weight: bold;
  color: rgb(68, 68, 68);;
}

.reply-desc .desc {
  margin-left: 5px;
  font-size: 20px;
  color: rgb(68, 68, 68);
  line-height: 21px;
}

.reply-desc .operator {
  margin-top: 5px;
  margin-left: 5px;
  font-size: 18px;
  color: #999;
  padding-bottom: 10px;
  user-select:none;
}

.el-icon-star-on {
  color: rgb(14, 118, 231);
}

.reply-desc .operator .reply-time {
  float: right;
  color: #C0C0C0;
  font-size: 18px;
}

.edit-reply-title {
  border-bottom: 1px solid #DCDFE6;
  margin-top: 30px;
  font-size: 25px;
  padding-bottom: 10px;
}

.edit-reply {
  width: 100%;
  padding-top: 30px;
}

.creator-msg {
  margin-bottom: 20px;
}

.submit-area {
  height: 50px;
  margin-top: 20px;
  margin-bottom: 20px;
}

#submit-btn {
  /* 右侧显示发布按钮 */
  float: right;
  
}

/* 作者标签 */
.auth-tag {
  margin-left: 10px;
  font-size: 14px;
  padding: 0px 4px;
  color: rgb(153, 153, 153);
  height: 16px;
  line-height: 16px;
  border: 1px solid;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

</style>